package com.mhy.soloader;

public class Register {

    /// <summary>
    /// 根据机器码生成注册码
    /// </summary>
    public static String regSerial(String machineSerial, boolean onlyNum) {
        return lockLogic(machineSerial, "SCIM-ENCE-SCIM-ENCE", onlyNum);
    }

    /// <summary>
    /// 对字符串Data用字符串Key进行加密
    /// </summary>
    private static String lockLogic(String Data, String Key, boolean onlyNum) {
        Data = Data.replaceAll("-", "").toUpperCase();
        Key = Key.replaceAll("-", "").toUpperCase();

        char[] data = Data.toCharArray();
        char[] key = Key.toCharArray();

        String tmp = "";
        for (int i = 0; i < data.length; i++) {
            tmp += onlyNum ? AlpahLock_Number(data[i], key[i % key.length]) : AlpahLock(data[i], key[i % key.length]);
        }
        return format(tmp);
    }

    /// <summary>
    /// 对字符C用K加密，转化为A-Z、0-9对应的字符
    /// </summary>
    private static char AlpahLock(char C, char K) {
        int n = (C + K) % 35;
        if (n < 26) return (char) (n + 'A'); // 0-25映射到 A-Z
        else return (char) (n - 26 + '1');   // 26-34映射到 1-9
    }

    /// <summary>
    /// 对字符C用K加密，转化为0-9对应的字符
    /// </summary>
    private static char AlpahLock_Number(char C, char K) {
        int n = (C + K) % 10;
        return (char) ('9' - n);  // 0-9映射到 9-0
    }

    /// <summary>
    /// 规整化字符串"BFEBFBFF000306A9"为"BFEB-FBFF-0003-06A9"
    /// </summary>
    public static String format(String Data) {
        Data = Data.toUpperCase();
        char[] data = Data.toCharArray();

        String tmp = "";
        for (int i = 0; i < data.length; i++) {
            tmp += data[i];
            tmp += (((i + 1) % 4 == 0 && i < data.length - 1) ? "-" : "");
        }
        return tmp;
    }
}
